<template>
  <div class="page-model">
    <el-form ref="formRef" :model="formModel" :rules="modelConfig.formRules" hide-required-asterisk>
      <el-row>
        <template v-for="item in modelConfig.formItems" :key="item.prop">
          <el-col :span="item.span ?? 24">
            <el-form-item :label="item.label" :prop="item.prop">
              <el-input
                v-if="item.type === 'input'"
                v-model="formModel[item.prop]"
                :placeholder="item.placeholder ?? '请输入'"
                :parser="item.parser ?? removeTrim"
                :formatter="item.formatter ?? removeTrim"
                clearable
              />
              <el-input
                v-else-if="item.type === 'password'"
                type="password"
                v-model="formModel[item.prop]"
                :show-password="item.showPassword"
                :placeholder="item.placeholder ?? '请输入'"
                :parser="item.parser ?? removeTrim"
                :formatter="item.formatter ?? removeTrim"
                clearable
              />
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
interface Iprops {
  modelConfig: {
    formItems: any[]
    formRules?: any
  }
}
const props = defineProps<Iprops>()
const initForm: any = {}
const formRef = ref()
for (const item of props.modelConfig.formItems) {
  if (item.prop) {
    initForm[item.prop] = item.initValue ? item.initValue : ''
  }
}
const formModel = reactive<any>(initForm)
for (const key in formModel) {
  const item = props.modelConfig.formItems.find((f) => f.prop === key)
  formModel[key] = item?.initValue ? item.initValue : ''
}

const emit = defineEmits(['DisabledChange'])
watch(
  () => formModel,
  () => {
    const rules = Object.keys(props.modelConfig.formRules ?? {})
    const hasValue = Object.values(formModel).every((item: any) => item)
    const isRequire = Object.keys(formModel).every((item: any) => rules.includes(item))
    const res = rules.length ? hasValue && isRequire : hasValue
    //检查表单项是否都有值
    if (res) {
      emit('DisabledChange', false) //不禁用
    } else {
      emit('DisabledChange', true) //禁用
    }
  },
  { deep: true },
)

const removeTrim = (value: any) => value.replace(/\s/g, '')
const clearForm = () => {
  for (const key in formModel) {
    if (key !== 'type' && key != 'state') {
      formModel[key] = ''
    }
    formRef.value?.resetFields()
  }
}
defineExpose({
  formRef,
  formModel,
  clearForm,
})
</script>
<style lang="less" scoped>
.page-model {
}
</style>
